package com.mdd.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.admin.LikeAdminThreadLocal;
import com.mdd.admin.service.IMediationTemplateService;
import com.mdd.admin.validate.MediationTemplateCreateValidate;
import com.mdd.admin.validate.MediationTemplateSearchValidate;
import com.mdd.admin.validate.MediationTemplateStateUpdateValidate;
import com.mdd.admin.validate.MediationTemplateUpdateValidate;
import com.mdd.admin.validate.commons.PageValidate;
import com.mdd.admin.vo.MediationTemplateDetailVo;
import com.mdd.admin.vo.MediationTemplateListedVo;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.MediationTemplate;
import com.mdd.common.mapper.MediationTemplateMapper;
import com.mdd.common.util.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * 调解书模板实现类
 * @author LikeAdmin
 */
@Service
public class MediationTemplateServiceImpl implements IMediationTemplateService {
        
    @Resource
    MediationTemplateMapper mediationTemplateMapper;

    /**
     * 调解书模板列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<MediationTemplateListedVo>
     */
    @Override
    public PageResult<MediationTemplateListedVo> list(PageValidate pageValidate, MediationTemplateSearchValidate searchValidate) {
        Integer page  = pageValidate.getPageNo();
        Integer limit = pageValidate.getPageSize();

        QueryWrapper<MediationTemplate> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("template_number");

        if (StringUtils.isNotEmpty(searchValidate.getKeyword())) {
            String keyword = searchValidate.getKeyword();
            queryWrapper.nested(wq->wq
                    .like("template_name", keyword).or()
                    .like("template_content", keyword));
        }

        if (StringUtils.isNotEmpty(searchValidate.getCreateTimeStart())
                && StringUtils.isNotEmpty(searchValidate.getCreateTimeEnd())) {
            queryWrapper.between("creation_time",searchValidate.getCreateTimeStart(),searchValidate.getCreateTimeEnd());
        }

        mediationTemplateMapper.setSearch(queryWrapper, searchValidate, new String[]{
            "=:contractType@contract_type:int",
            "=:templateState@template_state:long"
        });

        IPage<MediationTemplate> iPage = mediationTemplateMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<MediationTemplateListedVo> list = new LinkedList<>();
        for(MediationTemplate item : iPage.getRecords()) {
            MediationTemplateListedVo vo = new MediationTemplateListedVo();
            BeanUtils.copyProperties(item, vo);
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    /**
     * 调解书模板详情
     *
     * @author LikeAdmin
     * @param id 主键参数
     * @return MediationTemplate
     */
    @Override
    public MediationTemplateDetailVo detail(Integer id) {

        MPJQueryWrapper<MediationTemplate> mpjQueryWrapper = new MPJQueryWrapper<>();
        mpjQueryWrapper.selectAll(MediationTemplate.class).select("t2.nickname as founderName")
                .leftJoin("la_system_auth_admin t2 on t.founder = t2.id")
                .eq("template_number", id)
                .last("limit 1");
        MediationTemplateDetailVo vo = mediationTemplateMapper.selectJoinOne(MediationTemplateDetailVo.class, mpjQueryWrapper);
        Assert.notNull(vo, "数据不存在");
        if (vo.getCreationTime() != null) {
            vo.setCreationTimeStr(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(vo.getCreationTime()));
        }
        return vo;
    }

    /**
     * 调解书模板新增
     *
     * @author LikeAdmin
     * @param createValidate 参数
     */
    @Override
    public void add(MediationTemplateCreateValidate createValidate) {

        String username = LikeAdminThreadLocal.get("username").toString();

        MediationTemplate model = new MediationTemplate();
        model.setContractType(createValidate.getContractType());
        model.setTemplateName(createValidate.getTemplateName());
        model.setTemplateContent(createValidate.getTemplateContent());
        model.setTemplateState(createValidate.getTemplateState());
        model.setFounder(username);
        model.setCreationTime(new Date());
        model.setModifier(username);
        model.setModifierTime(new Date());
        model.setState(createValidate.getState());
        model.setFileId(createValidate.getFileId());
        model.setPositionX(createValidate.getPositionX());
        model.setPositionY(createValidate.getPositionY());
        model.setTemplateId(createValidate.getTemplateId());
        mediationTemplateMapper.insert(model);
    }

    /**
     * 调解书模板编辑
     *
     * @author LikeAdmin
     * @param updateValidate 参数
     */
    @Override
    public void edit(MediationTemplateUpdateValidate updateValidate) {
        MediationTemplate model = mediationTemplateMapper.selectOne(
                new QueryWrapper<MediationTemplate>()
                    .eq("template_number",  updateValidate.getTemplateNumber())
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        String username = LikeAdminThreadLocal.get("username").toString();
        model.setContractType(updateValidate.getContractType());
        model.setTemplateName(updateValidate.getTemplateName());
        model.setTemplateContent(updateValidate.getTemplateContent());
        model.setTemplateState(updateValidate.getTemplateState());
        model.setModifier(username);
        model.setModifierTime(new Date());
        model.setState(updateValidate.getState());
        model.setFileId(updateValidate.getFileId());
        model.setPositionX(updateValidate.getPositionX());
        model.setPositionY(updateValidate.getPositionY());
        model.setTemplateId(updateValidate.getTemplateId());
        mediationTemplateMapper.updateById(model);
    }

    @Override
    public void editState(MediationTemplateStateUpdateValidate updateValidate) {
        MediationTemplate model = mediationTemplateMapper.selectOne(
                new QueryWrapper<MediationTemplate>()
                        .eq("template_number",  updateValidate.getTemplateNumber())
                        .last("limit 1"));

        Assert.notNull(model, "数据不存在!");
        model.setTemplateState(updateValidate.getTemplateState().longValue());
        model.setState(updateValidate.getState().longValue());
        mediationTemplateMapper.updateById(model);
    }

    /**
     * 调解书模板删除
     *
     * @author LikeAdmin
     * @param id 主键ID
     */
    @Override
    public void del(Integer id) {
        MediationTemplate model = mediationTemplateMapper.selectOne(
                new QueryWrapper<MediationTemplate>()
                    .eq("template_number", id)
                    .last("limit 1"));

        Assert.notNull(model, "数据不存在!");

        mediationTemplateMapper.delete(new QueryWrapper<MediationTemplate>().eq("template_number", id));
    }

}
